// pages/submitOrder/submitOrder.js
import utils from '../../utils/util.js';
import {
  PATHS_ALIAS,
  OTHER_INFO
} from '../../utils/api.js'

import {
  http
} from '../../utils/network.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: '',
    unionId: '',
    headImgUrl:'',    //微信头像
    token: '', //token
    mobile: '',
    orderNo: '',     //提交订单生成的订单号
    ticketId: '', //票种ID
    activityId: '', //活动ID
    groupId: '', //团的id  参团必填，开团不填
    ticketDateArr: [], //票种日期选项
    ticketDateShowArr: [], //票种日期展示选项 3个
    ticketTimeArr: [], //票种时间选项
    ticketTimeId: '', //选择的票种时间ID
    buyNotesShow: false, //购买须知弹框显示
    actDetail: {}, //活动详情
    ticketInfo: {}, //票种信息
    choosePlayerShow: false, //选择联系人弹框显示
    contactList: [], //联系人列表
    chooseContactArr: [], //选中的联系人id数组
    agreeStatus: true, //免责声明
    orderDetail: {},   //订单数据
    formId:'',      //formId消息推送使用

    // 日历
    calendarShow: false, //日历弹框显示
    year: new Date().getFullYear(), // 年份-初始值
    month: new Date().getMonth() + 1, // 月份-初始值
    day: '', //选择的天数-初始值
    demo2_days_style: [], //日历-天样式
    activeDay: { //选择的票种日期
      year: '',
      month: '',
      day: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //console.log(options);
    // ticketId=1131&activityId=775
    this.setData({
      ticketId: options.ticketId,
      activityId: options.activityId,
      // ticketId: 1131 ,
      // activityId: 775,
      groupId: options.groupId ? options.groupId : '',
      token: wx.getStorageSync('accessToken'),
      mobile: wx.getStorageSync('mobile'),
      userId: wx.getStorageSync('userId'),
      unionId: wx.getStorageSync('unionId'),
      headImgUrl: wx.getStorageSync('userInfo').avatarUrl,
    });

    this.getTicketInfo();
    this.getTicketDate();
    this.getActDetail();
  },
  onShow: function () {
    let _this = this;
    this.getContactList();
    if (this.data.choosePlayerShow){    //如果选择联系人弹框存在，那么重新载入
      this.selectComponent('#choose_player').close();
      setTimeout(function(){
        _this.setData({
          choosePlayerShow:true
        })
      },200)
    }
  },
  onHide: function () {
    
  },
  // 选择日期
  chooseTicketDate: function (e) {
    // //console.log(e.currentTarget.dataset.date);
    let date = e.currentTarget.dataset.date;
    let activeDay = {
      year: date.substr(0, 4),
      month: date.substr(5, 2),
      day: date.substr(8, 2)
    };
    this.setData({
      activeDay
    });
    this.getTicketTime();
  },
  // 选择时间
  chooseTicketTime: function (e) {
    this.setData({
      ticketTimeId: e.currentTarget.dataset.id
    })
  },
  // 购买须知弹框显示
  buyNotesShow: function (e) {
    //console.log(e);
    this.setData({
      buyNotesShow: true
    })
  },
  // 购买须知弹框关闭
  closeBuyNotes: function (e) {
    // //console.log(e)
    this.setData({
      buyNotesShow: false
    })
  },
  // 选择联系人弹框显示
  choosePlayerShow: function () {
    this.setData({
      choosePlayerShow: true
    });
  },
  // 选择联系人弹框隐藏
  choosePlayerHide: function () {
    this.setData({
      choosePlayerShow: false
    })
  },
  // 选择联系人确定
  choosePlayerOk: function (e) {
    // //console.log(e)
    let chooseContactArr = e.detail.chooseArr;
    let contactList = e.detail.contactList;
    this.setData({
      chooseContactArr,
      contactList
    })
    this.choosePlayerHide();
  },
  // 免责声明选择
  agreeStatusChange: function () {
    this.setData({
      agreeStatus: !this.data.agreeStatus
    })
  },
  // 立即购买-表单提交
  formSubmit: function (e) {
    // console.log(e.detail.formId);
    // var _this = this;
    // 获取小程序全局唯一后台接口调用凭据（access_token）。调用各后台接口时都需使用 access_token，开发者需要进行妥善保存。
    // wx.request({
    //   url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbb59b4862d99c420&secret=b660fcb27c88c293b558c0c64e36ef1c',
    //   method: "GET",
    //   success: function (res) {
    //     console.log(res.data.access_token)
    //     wx.request({
    //       url: `https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=${res.data.access_token}`,
    //       method: "POST",
    //       data: {
    //         "touser": wx.getStorageSync('openId'),    //用户openId
    //         "template_id": "B0YnWB9y1Z8y8Zyekx99U_M4HVYhNTC0Tp7LwGTTVO8",     //模板消息ID
    //         "page": "/pages/index/index",      //点击模板卡片后的跳转页面,支持带参数
    //         "form_id": e.detail.formId,
    //         "data": {             //模板内容，不填则下发空模板
    //           "keyword1": {
    //             "value": "活动名称活动名称"
    //           },
    //           "keyword2": {
    //             "value": "开始时间开始时间开始时间"
    //           },
    //           "keyword3": {
    //             "value": "活动地点活动地点活动地点"
    //           },
    //           "keyword4": {
    //             "value": "温馨提示温馨提示"
    //           }
    //         },
    //         "emphasis_keyword": ""     //模板需要放大的关键词   keyword1.DATA
    //       },
    //       success: function (res) {
    //         console.log(res);

    //       }
    //     });


    //   }
    // });

    this.buyBtn();

  },
  // 立即购买
  buyBtn: function () {
    let ticketInfo = this.data.ticketInfo;
    if (ticketInfo.ticketCalendar == 'Y' && !this.data.ticketTimeId) {
      // 有活动日历 - 时间段必选
      wx.showToast({
        title: '请选择活动时间段',
        icon: 'none'
      });
      return;
    } else if (ticketInfo.ticketNum != this.data.chooseContactArr.length) {
      // 报名者数量不符
      wx.showToast({
        title: '请添加' + ticketInfo.ticketNum + '位报名者信息',
        icon: 'none'
      });
      return;
    } else if (!this.data.agreeStatus) {
      // 勾选《免费声明及退款说明》
      wx.showToast({
        title: '请勾选《免费声明及退款说明》',
        icon: 'none'
      });
      return;
    } else {
      // 去支付--1、重新获取token   2、提交订单   3、调用平台组支付接口   4、发起微信支付
      wx.showLoading({
        title: '支付中',
        mask: true
      });
      this.loginThird();
    }
  },
  // 重新获取token及用户信息，防止token失效
  loginThird: function () {
    let _this = this;
    let ticketId = this.data.ticketId;
    let activityId = this.data.activityId;
    let params = {
      logType: '07',
      thirdId: wx.getStorageSync('unionId'),
      resId: 'weixin',
      userSystem: '0052'
    };
    http({
      path: PATHS_ALIAS.THIRD_USER_LOGIN,
      params: params,
      header: {
        sendChl: 'hzsmk.h5', // 应用渠道(必填) 
        sendClient: 'hellohzsmk', //应用验证码(必填) string 
        clientCode: OTHER_INFO.clientCode
      },
      success: function (res) {
        //console.log(res);
        wx.setStorageSync('accessToken', res.response.accessToken);
        wx.setStorageSync('userId', res.response.userId);
        wx.setStorageSync('mobile', res.response.mobile);
        _this.setData({
          token: res.response.accessToken,
          mobile: res.response.mobile,
          userId: res.response.userId,
        });
        _this.placeOrder();
      },
      fail: function (err) {
        wx.hideLoading();
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        });
        //console.log(err);
        if (err.code == 'PY0005') { //跳转输入手机号登录
          let fromPage = encodeURIComponent(`/pages/submitOrder/submitOrder?ticketId=${ticketId}&activityId=${activityId}`)
          wx.redirectTo({
            url: `/pages/phoneLogin/phoneLogin?fromPage=${fromPage}`,
          })
        }
      },
      complete: function () {

      }
    })
  },
  // 提交订单
  placeOrder: function () {
    let _this = this;
    let params = {
      accessToken: wx.getStorageSync('accessToken'), //	用户令牌	string	必填
      activityId: this.data.activityId, //	活动ID	string	必填
      channelType: 'applet', //		smkapp-市民卡APP，weixin-微信，hztong-杭州通，alipay-支付宝，share-分享，applet-小程序
      contactIds: this.data.chooseContactArr, //	参加者信息	array<object>	
      groupId: this.data.groupId, //拼团订单的团ID	number	参团必填，开团不填
      mobile: wx.getStorageSync('mobile'), //	手机号	string	必填
      money: this.data.ticketInfo.ticketGroupPrice * 10 * 10, //	报名费金额单位分	string	必填
      realUserId: this.data.userId, //	统一用户userId	string	必填
      ticketId: this.data.ticketId, //	票种ID	string	非必填
      ticketTimeId: this.data.ticketTimeId, //	票种时间ID	string	非必填
      unionId:this.data.unionId,
      headImgUrl:this.data.headImgUrl
    };
    http({
      path: PATHS_ALIAS.CREATE_ORDER,
      params: params,
      success: function (res) {
        //console.log(res);
        //判断免费活动，免支付
        if (_this.data.ticketInfo.ticketGroupPrice == 0) {
          wx.redirectTo({
            url: '/pages/groupBuy/groupBuy?groupId=' + res.response.groupId,
          });
        } else {
          _this.setData({
            orderNo: res.response.orderNo
          });
          _this.aggPay(res.response.orderInfo);
        }
      },
      fail: function (err) {
        //console.log(err);
        wx.showToast({
          title: err.msg,
          icon: 'none'
        })
      }
    })

  },
  // 调用平台组统一支付接口
  aggPay: function (orderInfo) {
    let _this = this;
    let orderObj = JSON.parse(utils.base64DecodeUnicode(orderInfo));
    let orderNo = this.data.orderNo;
    // orderObj.order.thirdAppId = 'wxbb59b4862d99c420';
    //console.log(orderObj);
    let params = {
      openId: wx.getStorageSync('openId'), //	微信openid，微信公众号支付时必传	string	
      order: orderObj.order, //		订单信息	object	
      payType: 'WECHAT-SP', //		支付方式	string	支付宝h5：ALIPAY 微信h5：WECHAT 微信公众号：WECHAT-OA 支付宝app: ALIPAY - APP 微信app：WECHAT-APP，微信小程序：WECHAT-SP
      thirdAppid: OTHER_INFO.appId
    };
    http({
      path: PATHS_ALIAS.AGG_PAY,
      params: params,
      header: {
        accessToken: this.data.token,
        clientCode: OTHER_INFO.clientCode, //测试100001 验证用 300016
        sendChl: 'hzsmk.h5', // 应用渠道(必填) 
        sendClient: 'hellohzsmk', //应用验证码(必填) string  
        sendDev: 'test', //设备号(必填) string  
        serialSeq: new Date().getTime() + this.data.userId, //流水号(必填) string
        userName: this.data.mobile
      },
      success: function (res) {
        //console.log(res);
        let tn = JSON.parse(res.response.tn);
        let paySign = tn.sign;
        //console.log(tn)
        wx.hideLoading();
        // 调用微信支付
        wx.requestPayment({
          'timeStamp': tn.timeStamp + "", //new Date().getTime(),
          'nonceStr': tn.nonce_str, //Math.random().toString(36).substr(2),
          'package': "prepay_id=" + tn.prepay_id, //'prepay_id=*',
          'signType': 'MD5',
          'paySign': paySign,
          'success': function (res) {
            // 支付成功后
            console.log('支付成功:' + JSON.stringify(res));
            _this.confirmGroupOrder('success');
          },
          'fail': function (err) {
            console.log(err);
            // 支付失败，或取消支付.跳转到订单详情
            if (err.errMsg == 'requestPayment:fail cancel') {
              wx.showToast({
                title: '取消支付',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '支付失败',
                icon: 'none'
              });
            };
            wx.redirectTo({
              url: '/pages/orderDetail/orderDetail?orderNo=' + orderNo,
            })
          }
        })
      },
      fail: function (err) {
        // //console.log(err);
        wx.hideLoading();
        wx.showToast({
          title: err.msg,
          icon: 'none'
        });
        wx.redirectTo({
          url: '/pages/orderDetail/orderDetail?orderNo=' + orderNo,
        })
      }
    })
  },
  // 确认订单--支付成功回调   success-支付成功，fail-支付失败
  confirmGroupOrder: function (orderStatus) {
    let _this = this;
    let orderNo = this.data.orderNo;
    let params = {
      mobile: this.data.mobile,    //	手机号	string	必填
      orderNo: orderNo,    //		订单号	string	必填
      orderStatus: orderStatus,    //		订单状态	string	必填，，success-支付成功，fail-支付失败
      realUserId: this.data.userId,    //		统一用户userId	string	必填
    };
    http({
      path: PATHS_ALIAS.CONFIRM_GROUP_ORDER,
      params: params,
      success: function (res) {
        //console.log(res)
        if (_this.data.groupId) {   //参团订单--跳转到拼团详情
          wx.redirectTo({
            url: `/pages/groupBuy/groupBuy?groupId=${_this.data.groupId}`,
          })
        } else {    //开团订单--跳转到订单详情
          wx.redirectTo({
            url: '/pages/orderDetail/orderDetail?orderNo=' + orderNo,
          })
        }
      },
      fail: function (err) {
        //console.log(err)
        wx.redirectTo({
          url: '/pages/orderDetail/orderDetail?orderNo=' + orderNo,
        })
      }
    })

  },
  // 设置日期选择快捷按钮、默认选中项
  setDefaultDate: function () {
    // 获取票种日期选项 --前三个
    let ticketDateShowArr = [];
    let ticketDateArr = this.data.ticketDateArr;
    for (let i = 0; i < 3; i++) {
      if (ticketDateArr[i]) {
        ticketDateShowArr.push(ticketDateArr[i]);
      }
    };
    let activeDay = {
      year: ticketDateShowArr[0].ticketDate.substr(0, 4),
      month: ticketDateShowArr[0].ticketDate.substr(5, 2),
      day: ticketDateShowArr[0].ticketDate.substr(8, 2)
    };
    this.setData({
      ticketDateShowArr,
      activeDay
    });
    this.getTicketTime();
  },
  // 获取票种信息
  getTicketInfo: function () {
    let _this = this;
    let params = {
      activityId: this.data.activityId, //	活动ID	number	必填
      ticketId: this.data.ticketId, //	票种ID	number	必填
    };
    http({
      path: PATHS_ALIAS.GET_TICKET_INFO,
      params: params,
      success: function (res) {
        //console.log(res)
        _this.setData({
          ticketInfo: res.response.ticketInfo
        })
      },
      fail: function (err) {
        //console.log(err)
      }
    })
  },
  // 获取票种日期
  getTicketDate: function () {
    let _this = this;
    let params = {
      activityId: this.data.activityId, //	活动ID	number	必填
      ticketId: this.data.ticketId, //	票种ID	number	必填
      groupBuy:'Y'
    };
    http({
      path: PATHS_ALIAS.GET_TICKET_DATE,
      params: params,
      success: function (res) {
        // //console.log(res)
        let ticketDateArr = res.response.ticketDatelist;
        if (ticketDateArr.length < 1) {
          return;
        }
        _this.setData({
          ticketDateArr: res.response.ticketDatelist
        });
        _this.setDefaultDate();
      },
      fail: function (err) {
        //console.log(err)
      }
    })
  },
  // 获取票种时间
  getTicketTime: function () {
    let _this = this;
    let activeDay = this.data.activeDay;
    //console.log(activeDay);
    let ticketDate = activeDay.year + '-' + this.doubleNum(parseInt(activeDay.month)) + '-' + this.doubleNum(parseInt(activeDay.day));
    let params = {
      activityId: this.data.activityId, //	活动ID	number	必填
      ticketDate: ticketDate, //	票种日期	string	必填
      ticketId: this.data.ticketId, //	票种ID	string	必填
      groupBuy:'Y'
    };
    http({
      path: PATHS_ALIAS.GET_TICKET_TIME,
      params: params,
      success: function (res) {
        //console.log(res)
        _this.setData({
          ticketTimeArr: res.response.ticketTimelist, //票种时间选项
          ticketTimeId: res.response.ticketTimelist.length == 1 ? res.response.ticketTimelist[0].ticketTimeId:''
        });
      },
      fail: function (err) {
        //console.log(err)
      }
    })

  },
  // 获取活动详情
  getActDetail: function () {
    let _this = this;
    let params = {
      activityId: this.data.activityId
    };
    http({
      path: PATHS_ALIAS.GET_GROUP_ACT_DETAIL,
      params: params,
      success: function (res) {
        _this.setData({
          actDetail: res.response.groupActDetail
        });
        _this.filterTicketTime();
      },
      fail(err) {

      }
    });
  },
  // 计算票种报名时间及状态
  filterTicketTime() {
    let _this = this;
    let ticketInfo = this.data.ticketInfo;
    let actDetail = this.data.actDetail;

    if (actDetail.ticketCalendar == 'Y') { //有日历，计算最早报名时间
      let nearestBookDay = ticketInfo.nearestBookTime ? ticketInfo.nearestBookTime.slice(0, 10) : '';
      if (nearestBookDay) {
        let today, nearDay, timeInterval;
        today = utils.formatTime(new Date()).slice(0, 10);
        nearDay = nearestBookDay.replace(/-/g, '/');
        timeInterval = new Date(nearDay) - new Date(today);
        if (timeInterval == 0) {
          ticketInfo.ticketStatusTxt = '最早可预订今天';
        } else if (timeInterval == 24 * 60 * 60 * 1000) {
          ticketInfo.ticketStatusTxt = '最早可预订明天';
        } else {
          nearDay = new Date(nearDay);
          ticketInfo.ticketStatusTxt = "最早可订" + (nearDay.getMonth() + 1) + "月" + nearDay.getDate() + "日";
        }
      };
      ticketInfo.ticketStatus = 'filterTime' //票种状态  filterTime（最早报名时间） full（名额已满） end(报名结束)
    } else if (ticketInfo.entryNumFull == 'Y') { //票种名额已满
      ticketInfo.ticketStatus = 'full'
      ticketInfo.ticketStatusTxt = ''
    } else if (actDetail.entryNumFull == 'N' && actDetail.entryStatus == 'end') { //票种报名时间已结束
      ticketInfo.ticketStatus = 'end'
      ticketInfo.ticketStatusTxt = ''
    } else { } //没有票种日历不展示
    this.setData({
      ticketInfo
    })
  },
  // 获取联系人列表
  getContactList: function () {
    let _this = this;
    let params = {
      activityId: this.data.activityId, //	活动ID	number	必填
      userId: this.data.userId, //	用户ID	string	必填
    };
    http({
      path: PATHS_ALIAS.GET_CONTACTS_LIST,
      params: params,
      success: function (res) {
        //console.log(res);
        let contactList = res.response.contactList ? res.response.contactList : []; //联系人列表
        _this.setChooseData(contactList);
      },
      fail: function (err) {
        //console.log(err)
      }
    })

  },
  // 设置联系人选中字段 checked
  setChooseData: function (contactList) {
    let _this = this;
    let chooseArr = this.data.chooseContactArr; //已选中的联系人id
    let ticketInfo = this.data.ticketInfo;
    let actElementList = ticketInfo.actElementList; //报名需要的信息

    if (JSON.stringify(ticketInfo) == '{}') { //解决异步问题
      setTimeout(function () {
        _this.setChooseData(contactList);
      }, 50)
      return;
    }


    contactList.forEach(function (itemA, indexA) {
      // 判断是否选中
      let itemChecked = false;
      chooseArr.forEach(function (itemB, indexB) {
        if (itemA.id == itemB) {
          itemChecked = true;
        }
      });
      contactList[indexA].checked = itemChecked;

      // 判断是否需要补全信息
      for (let i = 0; i < actElementList.length; i++) {
        let key = actElementList[i].actElementCode;
        contactList[indexA].infoEnough = true;
        if (!itemA[key]) {
          contactList[indexA].infoEnough = false;
          break;
        };
      }
    });
    this.setData({
      contactList
    });
  },

  // 阻止事件冒泡--空事件
  stopDefault: function () { },
  // 日历有关----start ------------------------------------------------------------------------
  // 日历弹框显示
  calendarShow: function () {
    let activeDay = this.data.activeDay;
    this.setData({
      calendarShow: true,
      year: activeDay.year,
      month: activeDay.month
    });
    this.initCalendar();
  },
  // 日历弹框隐藏
  calendarHide: function () {
    this.setData({
      calendarShow: false
    })
  },
  // 初始化日历-样式赋值 
  initCalendar: function () {
    const days_count = new Date(this.data.year, this.data.month, 0).getDate();
    let activeDay = this.data.activeDay;
    let year = this.data.year; // 年份-
    let month = this.data.month; // 月份-
    let demo2_days_style = new Array;

    // 过滤出当前月份的可选日期
    let daysArr = this.data.ticketDateArr.filter(function (item, index) {
      if (item.entryNumFull == 'N' && item.ticketDate.indexOf(year + '-' + month) > -1) {
        return true;
      }
    });
    //console.log(year + '-' + month, daysArr);
    for (let i = 1; i <= days_count; i++) {
      if (this.filterData(i, daysArr)) {
        demo2_days_style.push({
          month: 'current',
          day: i,
          color: '#333333',
        });
      } else {
        demo2_days_style.push({
          month: 'current',
          day: i,
          color: '#c3c6d1',
          background: '#fafafa'
        });
      }
    };
    // 选中的日期样式
    if (year == activeDay.year && month == activeDay.month && activeDay.day) {
      let activeDayStyle = {
        month: 'current',
        day: activeDay.day,
        color: '#ffffff',
        background: '#f4545f'
      };
      demo2_days_style[activeDay.day - 1] = activeDayStyle;
    };
    this.setData({
      demo2_days_style
    });
  },
  // 筛选可选日期
  filterData: function (i, daysArr) {
    // //console.log(daysArr);
    for (let j = 0; j < daysArr.length; j++) {
      if (i == daysArr[j].ticketDate.substr(-2, 2)) {
        return true;
        break;
      }
    }
  },
  // 月份改变
  monthChange: function (e) {
    //console.log(e.detail);
    this.setData({
      year: e.detail.currentYear,
      month: e.detail.currentMonth
    });
    this.initCalendar();
  },
  // 日期选择--某一天
  dayClick: function (e) {
    if (e.detail.color.indexOf('#333333') < 0 && e.detail.color.indexOf('#ffffff') < 0) {
      return
    }
    let activeDay = {
      year: e.detail.year,
      month: e.detail.month,
      day: e.detail.day
    };
    this.setData({
      day: e.detail.day,
      activeDay
    });
    this.getTicketTime();

    let ticketDateShowArr = this.data.ticketDateShowArr;
    let noThisDate = true;
    for (let i = 0; i < ticketDateShowArr.length; i++) {
      let item = ticketDateShowArr[i];
      if (activeDay.year + '-' + activeDay.month + '-' + activeDay.day == item.ticketDate) {
        noThisDate = false;
      }
    };
    if (noThisDate) { //三个快速选择日期没有选中的，修改第三个日期
      ticketDateShowArr[2] = {
        "entryNumFull": "N",
        "ticketDate": activeDay.year + '-' + activeDay.month + '-' + activeDay.day
      };
      this.setData({
        ticketDateShowArr
      })
    }

    this.calendarHide();
    this.initCalendar();
  },
  // 日历有关----end ------------------------------------------------------------------------
  // 一位数字前面加0
  doubleNum: function (num) {
    let res = '';
    if (parseInt(num) < 10) {
      res = '0' + num;
    } else {
      res = num;
    };
    return res;
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})